package com.spring.core.scan;

import com.spring.core.context.AbstractApplicationContext;

import java.io.File;
import java.net.URL;

/**
 * 扫描类文件
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/13
 */
public class ComponentScanner implements Scanner {


    @Override
    public void doScanner(String scanPackage, AbstractApplicationContext context) {
        System.out.println("扫描" + scanPackage + "路径下的class文件...");
        scan(scanPackage, context);
    }

    /**
     * 扫描文件
     *
     * @param scanPackage 扫描路径
     * @param context     spring 容器
     */
    private void scan(String scanPackage, AbstractApplicationContext context) {
        URL url = this.getClass().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        if (null == url) {
            return;
        }
        File classPath = new File(url.getFile());
        for (File f : classPath.listFiles()) {
            if (f.isDirectory()) {
                scan(scanPackage + "." + f.getName(), context);
            } else {

                if (!f.getName().endsWith(".class")) {
                    continue;
                }

                String className = scanPackage + "." + f.getName().replace(".class", "");
                System.out.println("    "+className);
                context.getClassNames().add(className);
            }
        }
    }

}
